const router = require('koa-router')()
var request = require('request');
router.prefix('/common')

var appId = 'wxc5ee705c32731501';
var sessionKey = 'f8c764715f491f54244ee2f4edeb5f28';

// let DB = require('../../model/tpzdz/index')
// let AUTHORI = require("../../model/tpzdz/authorization");

const uuidv1 = require('uuid/v4');

/**
 * @api {post} /getOppenId 获得oppenId
 * @apiGroup common
 * @apiParam {String} [code]  code
 * @apiSampleRequest http://192.168.121.12/tpzdz/admin
 * @apiSuccess {json} result
 * @apiSuccessExample {json} Success-Response:
 *{
 * "session_key":"8s3xpwd6s3V0rD9G6xWF4w==",
 * "openid":"oYwQJ49HiXEFUK7q1yzm4n09TE6c"
 * }
 */
router.post('/getOppenId', async (ctx, next) => {
  console.log('获得getOppenId')
  let openid = ''
  // ctx.response.body = {status:200,msg:'这是post测试的返回数据'};
  var opts = {
    headers: Object.assign({
      'Connection': 'close',
      'Content-Type': 'application/json; charset=utf-8',
      'node': 'open'
    }),
    method: 'get',
    url: `https://wx.linktodeal.com/sns/info?app=${ctx.request.body.app}&code=${ctx.request.body.code}`,
    json: true,
    body: ctx.request.body
  };
  let result = await getToken(opts)

  if (result.code !== 0) {
    console.log('----', result)
    ctx.body = {
      code: -1,
      msg: '获得token失败',
      errMsg: result
    }
    return
  }
  let has = await AUTHORI.findOne({
    where: {
      openId: result.data.openid
    }
  }).then(r => {
    return r
  }).catch(err => {
    console.log(err)
    return -1
  })
  if (has === -1) {
    ctx.body = {
      code: -1,
      msg: '获取失败'
    }
    return
  }
  let data = null
  if (!has) {
    data = await AUTHORI.create({
      openId: result.data.openid
    }).then((rdata) => {
      console.log('插入成功')
      return {
        openId: result.data.openid
      }
    }).catch(err => {
      console.log(err)
      return false
    })
    if (data === false) {
      ctx.body = {
        code: -1,
        msg: '获取失败'
      }
      return
    }
  }
  ctx.body = result
});

module.exports = router

function getToken(opts) {
  return new Promise(function (resolve, reject) {
    request(opts, function (error, response, body) {
      if (error) {
        return reject(error);
      }
      var result = undefined;
      if (response.statusCode.toString().indexOf('20') == 0) {
        result = body;
      } else {
        result = {
          errorCode: "01",
          description: "服务器内部错误",
          msg: body
        };
      }
      resolve(result);
    });
  });
}
